Supporting Information for: Phylogenetic generalised linear mixed-effects modelling with glmmTMB R package

Author

Coralie Williams, Maeve McGillycuddy, Szymek Drobniak, Ben Bolker, David I. Warton, Shinichi Nakagawa

1 Overview

Code
knitr::opts_chunk$set(
  warning = FALSE,
  message = FALSE
)

pacman::p_load(
  rmarkdown, readr, dplyr, purrr, splitstackshape, tidyverse, tidyr, ggplot2,
  vroom, details, sessioninfo, devtools, readxl, forcats, stringr, ape, phytools, 
  geiger, data.table, pavo, MASS, glmmTMB, brms, MCMCglmm, phyr, INLA, broom.mixed,
  knitr, bayestestR, performance, rbenchmark, here, DHARMa, emmeans, purrr
)

options(digits = 4, scipen = 5)

This webpage provides supporting information for the manuscript “Phylogenetic generalised linear mixed-effects modelling with the glmmTMB R package”, where we showcase the propto (proportional-to) covariance structure in the glmmTMB R package (McGillycuddy, 2023; Kristensen & McGillycuddy, 2025).

This webpage is organised in three sections:

  1. First, we describe the simulated models and data-generating mechanisms for each of the five evaluated R packages for fitting PGLMMs (see Models).

  2. We then use the simulated data to illustrate compilation and sampling runtimes for the Bayesian MCMC models (see Runtimes).

  3. Finally, we present two case studies that apply these methods to ecological and evolutionary data, the first on bird colour traits and the second on plant traits (see Case studies).

Contact

For questions or error reports, contact Coralie Williams: coralie.williams@unsw.edu.au or coraliewilliams@outlook.com

Last updated on: 02 September 2025

2 Models

We demonstrate and explain how to fit phylogenetic generalized mixed models (PGLMM) using five different packages which we used in our simulation study: glmmTMB, phyr, MCMCglmm, brms, and INLA. The models are fitted to one simulated dataset using a randomly generated phylogenetic tree and a set of model parameters. We compare the performance of these packages in terms of runtime, accuracy, and bias of the fixed effect mean and random effect variance estimates.

We assume a set of trait measures \(y_{ij}\) repeated measure (observation) \(i\) and for each species \(j\). The model is specified as follows:

\[ y_{ij} = \beta_0 + \beta_1 x_{ij} + n_j + p_j + \varepsilon_{ij} \]

Where:

  • \(y_{ij}\): trait response for measure (observation) \(i\) in species \(j\)
  • \(\beta_0, \beta_1\): fixed effects (intercept and slope)
  • \(n_i \sim \mathcal{N}(0, \sigma^2_{\text{n}})\): species-level effect (non-phylogenetic)
  • \(p_i \sim \mathcal{N}(0, \sigma^2_{\text{p}} \mathbf{A})\): species-level effect (phylogenetic), where \(\mathbf{A}\) is the phylogenetic correlation matrix
  • \(\varepsilon_{ij} \sim \mathcal{N}(0, \sigma^2_{e})\): residual error

2.1 Simulate data

First we specify the parameter values for one simulation run. We assume the following:

Code
### set up model parameters 
seed <- 1         
b0 <- 1           # fixed effect intercept
b1 <- 1.5         # fixed effect slope
k.species <- 30   # number of species
n.reps <- 10      # number of repeated measures per species (assuming a balanced design)
sigma2.n <- 0.25  # variance of non-phylogenetic effect
sigma2.p <- 0.25  # variance of phylogenetic effect
sigma2.e <- 0.2   # residual error variance

Simulate data based on these parameter values:

Code
set.seed(seed)

# set up k.obs (number of observations per species)
k.obs <- n.reps # assumes a balanced design
# species id 
sp.id <- rep(seq_len(k.species), times=k.obs)
# total number of observations
n <- length(sp.id)

# simulate simple dataframe with covariate (x) variable
x <- runif(n, 10, 20) 
dat <- data.frame(obs = 1:n, x = x, species = sp.id)

# simulate tree and obtain phylo matrix
tree <- ape::rtree(k.species, tip.label = seq_len(k.species))
tree <- ape::compute.brlen(tree, power=1) # power of 1 means ultra-metric tree
phylo.mat <- ape::vcv(tree, corr = TRUE) # we want a correlation matrix (bounded by -1 and 1) ultrametric tree
phylo.mat <- phylo.mat[order(as.numeric(rownames(phylo.mat))), order(as.numeric(rownames(phylo.mat)))]


# Simulate response variable (phen) based on cofactor and phylogenetic matrix
u.s <- rnorm(k.species, 0, sqrt(sigma2.n))[sp.id]
u.p <- MASS::mvrnorm(1, mu=rep(0, k.species), Sigma=sigma2.p*phylo.mat)[sp.id]
ei <- rnorm(n, 0, sqrt(sigma2.e))

# get estimates of y
yi <- b0 + b1*x + u.s + u.p + ei

### append all to dataframe
dat <- cbind(dat, u.s, u.p, ei, b0, b1, yi)
dat$phylo <- dat$species # phylo ID variable (same as species) - needs to be numeric to work with INLA
dat$species <- factor(dat$species) # format species variable for models
dat$sp <- dat$species # create sp variable (for phyr)
dat$g <- 1 # add variable g constant (for glmmTMB)

save(dat, tree, phylo.mat, file = "simulated_data.RData")

View first five rows of the simulated dataset:

Code
head(dat)
  obs     x species     u.s      u.p       ei b0  b1    yi phylo sp g
1   1 12.66       1  0.2103  0.18051  0.17637  1 1.5 20.55     1  1 1
2   2 13.72       2 -0.2001  0.62222 -0.38096  1 1.5 21.62     2  2 1
3   3 15.73       3 -0.6851 -0.48357  1.18474  1 1.5 24.61     3  3 1
4   4 19.08       4  0.4939  0.07762  0.06977  1 1.5 30.26     4  4 1
5   5 12.02       5  0.7599 -0.24698  0.50544  1 1.5 20.04     5  5 1
6   6 18.98       6 -0.1544  0.08753 -1.02373  1 1.5 28.39     6  6 1

2.2 Run models

Run model with glmmTMB

To fit a PGLMM using glmmTMB package we specify the species-level random effect with phylogenetic relatedness using the propto covariance structure. In the first part we specify the random intercept (0 + species), followed by the grouping variable g (which we assume here as constant), and then the phylogenetic correlation matrix phylo.mat.

The model output will provide the fixed effect estimates, random effect variance estimates, and the residual variance estimate. The random effect variance estimates will be on the standard deviation scale, so we square them to get the variance estimates.

Code
# repeated measures per species
time.glmmTMB <- system.time({
  model_glmmTMB <- glmmTMB(yi ~ x + (1|species) + propto(0 + species|g, phylo.mat),
                           data = dat,
                           REML = TRUE)
})

Check if the model converged (i.e. returns TRUE if the Hessian is positive definite, for more details read here: https://cran.r-project.org/web/packages/glmmTMB/vignettes/troubleshooting.html):

Code
model_glmmTMB$sdr$pdHess
[1] TRUE

We can then get the fixed effect estimates and their confidence intervals:

Code
coefs_tmb <- as.data.frame(confint(model_glmmTMB, parm="beta_"))
coefs_tmb
              2.5 % 97.5 % Estimate
(Intercept) 0.05789  1.614    0.836
x           1.49053  1.530    1.510

The random effect component estimates are on the standard deviation scales fron the confint function, so we need to square them to get the variance estimates. We also compute the standard error and confidence intervals on the variance scale using the delta method.

Code
re_tmb <- as.data.frame(confint(model_glmmTMB, parm="theta_")) # on standard deviation scale
re_tmb
                             2.5 % 97.5 % Estimate
Std.Dev.(Intercept)|species 0.2310 0.5708   0.3631
Std.Dev.species1|g          0.3353 1.2740   0.6535
Code
# Compute variance, SE (delta method), and CI on variance scale)
var_est <- re_tmb$Estimate^2
var_se <- 2 * re_tmb$Estimate * (re_tmb$`97.5 %` - re_tmb$`2.5 %`) / (2 * 1.96)
var_ci_low <- re_tmb$`2.5 %`^2
var_ci_high <- re_tmb$`97.5 %`^2

# Residual variance
resid_var <- sigma(model_glmmTMB)^2

# Combine results
sigma2_tmb <- data.frame(
  model = "glmmTMB",
  group = c("phylo", "species", "Residual"),
  term = "var",
  estimate = c(var_est, resid_var),
  std.error = c(var_se, NA),
  conf.low = c(var_ci_low, NA),
  conf.high = c(var_ci_high, NA))

sigma2_tmb
    model    group term estimate std.error conf.low conf.high
1 glmmTMB    phylo  var   0.1319   0.06294  0.05337    0.3258
2 glmmTMB  species  var   0.4271   0.31301  0.11239    1.6230
3 glmmTMB Residual  var   0.2060        NA       NA        NA

Run model with phyr

To fit the model using phyr package we use the cov_ranef argument to specify the phylogenetic tree directly. The random effect term (1|sp__) indicates that we want to include both phylogenetic and non-phylogenetic random effects. The underscores __ indicate that we want to include phylogenetic correlations in the model.

Code
time.phyr <- system.time({
  model_phyr <- pglmm(yi ~ x + (1|sp__),
                      cov_ranef = list(sp = tree),
                      data = dat,
                      REML = TRUE)
})

Obtain fixed effect estimates from model:

Code
coefs_phyr <- as.data.frame(fixef(model_phyr))
coefs_phyr$conf.low[2] <- coefs_phyr$Value[2] - coefs_phyr$Std.Error[2]*1.96
coefs_phyr$conf.high[2] <- coefs_phyr$Value[2] + coefs_phyr$Std.Error[2]*1.96

Obtain the random effect and residual variance estimates. Note that phyr provides them on the standard deviation scale.

Code
# get phyr random effect variance estimates 
var_re_phyr <- c(as.numeric(model_phyr$ss[2])^2, #phylogenetic 
                 as.numeric(model_phyr$ss[1])^2, #non-phylogenetic 
                 as.numeric(model_phyr$ss[3])^2) #residual 


# combine into dataframe
sigma2_phyr <- data.frame(
  model = "phyr",
  group = c("phylo", "species", "Residual"),
  term = "var",
  estimate = var_re_phyr,
  std.error = NA,
  conf.low = NA, 
  conf.high = NA 
)

sigma2_phyr
  model    group term estimate std.error conf.low conf.high
1  phyr    phylo  var   0.3459        NA       NA        NA
2  phyr  species  var   0.6390        NA       NA        NA
3  phyr Residual  var   0.2060        NA       NA        NA

Run model with MCMCglmm

To fit the MCMCglmm model we first we need to set up a precision matrix for the phylogenetic random effect, which (which is the inverse of the phylogenetic covariance matrix). We use the inverseA function the package to obtain the inverse of the phylogenetic covariance matrix.

These priors specify weakly informative settings: both random effects (\(G1\), \(G2\)) use inverse-Wishart style priors (\(V=1\), \(\nu=1\), with \(\alpha.\mu=0\), \(\alpha.V=1000\)), while the residual variance (\(R\)) has an almost flat inverse-Gamma prior (\(V=1\), \(\nu=0.02\)).

The ginverse argument is used to specify the inverse of the phylogenetic covariance matrix. Then we specify the number of iterations, burn-in, and thinning parameters for the MCMC sampling. Here we increased the number of iterations by 30 times the default value to ensure convergence and stability of the MCMC chains, but this could be further increased. Usually you would want to set these to some reasonably large values after inspection of diagnostic plots (i.e. trace plots and posterior distributions).

Code
# get precision phylo matrix and order rows
phylo.prec.mat <- MCMCglmm::inverseA(tree, nodes = "TIPS", scale = TRUE)$Ainv
phylo.prec.mat <- phylo.prec.mat[order(as.numeric(rownames(phylo.prec.mat))),
                                 order(as.numeric(rownames(phylo.prec.mat)))]

# set priors for two random effects
prior <- list(G=list(G1=list(V=1,nu=1,alpha.mu=0,alpha.V=1000), 
                     G2=list(V=1,nu=1,alpha.mu=0,alpha.V=1000)),
              R=list(V=1,nu=0.02))

# fit MCMCglmm model
time.mcmc <- system.time({
  model_mcmc <- MCMCglmm(yi ~ x,
                         random = ~species + phylo,
                         family = "gaussian",
                         ginverse = list(phylo = phylo.prec.mat),
                         prior = prior,
                         data = dat,
                         verbose = FALSE,
                         nitt = 303000, # increase default by x30
                         burnin = 3000, # default
                         thin = 10) # default
})

Plot the trace plots of the parameters to check for convergence. We expect to see good mixing of the chains and no trends.

Code
plot(model_mcmc$Sol, ask = FALSE)

Next we check the effective sample size (ESS). The ESS should be above 400 for both fixed and random effects and the Rhat value should be below 1.01 (Vehtari et al., 2021).

Code
min(effective_sample(model_mcmc, effects = "fixed")$ESS)
[1] 30000
Code
min(effective_sample(model_mcmc, effects = "random")$ESS)
[1] 3239

We can also check the Heidelberger diagnostic test which checks if the MCMC chains have converged and are stationary ( we expect to see ‘passed’ for all parameters). In practice it is important to inspect diagnostic plots of the Markov chains and posterior distributions.

Code
fullchain <- cbind(as.mcmc(model_mcmc$Sol), as.mcmc(model_mcmc$VCV))
heidel.diag(fullchain)
                                          
            Stationarity start     p-value
            test         iteration        
(Intercept) passed       1         0.184  
x           passed       1         0.580  
species     passed       1         0.767  
phylo       passed       1         0.855  
units       passed       1         0.490  
                                     
            Halfwidth Mean  Halfwidth
            test                     
(Intercept) passed    0.845 0.005440 
x           passed    1.510 0.000114 
species     passed    0.149 0.002052 
phylo       passed    0.660 0.017493 
units       passed    0.208 0.000203 

Obtain the fixed effect estimates with the tidy function:

Code
coefs_mcmc <- as.data.frame(tidy(model_mcmc, effects="fixed", conf.int=TRUE))
coefs_mcmc
  effect        term estimate std.error conf.low conf.high
1  fixed (Intercept)   0.8452   0.48078  -0.1162     1.815
2  fixed           x   1.5100   0.01007   1.4902     1.530

Obtain the random effect and residual variance estimates:

Code
# get MCMCglmm random effect estimates (variance scale)
sigma2_mcmc <- tidy(model_mcmc, effects="ran_pars", conf.int=TRUE)
sigma2_mcmc <- sigma2_mcmc %>%
  mutate(model="MCMCglmm",
         group=str_replace(group,"animal", "phylo")) %>% 
  dplyr::select(model, group, term, estimate, std.error, conf.low, conf.high)

sigma2_mcmc
# A tibble: 3 × 7
  model    group    term             estimate std.error conf.low conf.high
  <chr>    <chr>    <chr>               <dbl>     <dbl>    <dbl>     <dbl>
1 MCMCglmm species  var__(Intercept)    0.149    0.0812   0.0258     0.344
2 MCMCglmm phylo    var__(Intercept)    0.660    0.508    0.104      2.03 
3 MCMCglmm Residual var__Observation    0.208    0.0180   0.175      0.245

Run model with brms

To fit the model using the brms package we specify the random effects using the (1|species) term for non-phylogenetic random effects and gr(phylo, cov = phylo.mat) for phylogenetic random effects. The data2 argument is used to pass the phylogenetic correlation matrix to the model (the same matrix format as for glmmTMB). We set the number of iterations, chains, and cores to reasonable values to ensure convergence and stability of the MCMC chains. Here we increased the number of iterations by 10 times the default value to ensure convergence and stability of the MCMC chains, but this could be further increased (and should be if ESS are low and Rhat values are higher than 1.01).

Code
time.brms <- system.time({
  model_brms <- brm(yi ~ x + (1|species) + (1|gr(phylo, cov = phylo.mat)), #phylo.mat is the correlation matrix
                    data = dat,
                    family = gaussian(),
                    chains = 4, # default
                    iter = 20000, # increased default x10
                    cores = 4, # equal to number of chains
                    data2 = list(phylo.mat = phylo.mat))
})

Look at the trace plots of the parameters to check for convergence. We expect to see good mixing of the chains and no trends.

Code
plot(model_brms, N = 2, ask = FALSE)

Check that the maximum effective sample size (ESS) of the model is high enough and check the Rhat value is below 1.01 (Vehtari et al. 2021).

Code
# check ESS 
min(bayestestR::effective_sample(model_brms, effects = "fixed")$ESS)
[1] 29180
Code
min(bayestestR::effective_sample(model_brms, effects = "random")$ESS)
[1] 8995
Code
# check RHat value is below 1.01 (Vehtari et al. 2021)
max(rhat(model_brms))<1.01
[1] TRUE
Code
# alternatively, we can use the bayestestR package to check the diagnostics of fixed effects
print(bayestestR::diagnostic_posterior(model_brms), digits = 4)
    Parameter   Rhat   ESS       MCSE
1 b_Intercept 1.0000 29180 0.00279093
2         b_x 0.9999 95469 0.00003247

We can also use the diagnostic test from the bayestestR package to check the convergence of the MCMC chains.

Code
print(bayestestR::diagnostic_posterior(model_brms),
digits = 4)
    Parameter   Rhat   ESS       MCSE
1 b_Intercept 1.0000 29180 0.00279093
2         b_x 0.9999 95469 0.00003247

Obtain the fixed effect estimates with tidy function:

Code
coefs_brm <- as.data.frame(tidy(model_brms, effects="fixed", conf.int=TRUE))
coefs_brm
  effect component        term estimate std.error conf.low conf.high
1  fixed      cond (Intercept)   0.8433   0.47675  -0.1189     1.811
2  fixed      cond           x   1.5101   0.01003   1.4905     1.530

Obtain the random effect and residual variance estimates:

Code
sigma_brms <- tidy(model_brms, effects="ran_pars")
sigma2_brms <- sigma_brms %>%
  mutate(model="brms",
         term=str_replace(term, "sd", "var"),
         estimate=estimate^2) %>%     ##compute variance estimates
  dplyr::select(model, group, term, estimate, std.error, conf.low, conf.high)

sigma_brms
# A tibble: 3 × 8
  effect   component group    term         estimate std.error conf.low conf.high
  <chr>    <chr>     <chr>    <chr>           <dbl>     <dbl>    <dbl>     <dbl>
1 ran_pars cond      phylo    sd__(Interc…    0.768    0.285     0.323     1.44 
2 ran_pars cond      species  sd__(Interc…    0.371    0.106     0.154     0.586
3 ran_pars cond      Residual sd__Observa…    0.456    0.0200    0.419     0.497

Run model with INLA

For the INLA package we set up the model using the f() function to specify the random effects. The model = "iid" argument indicates that we want to use an independent and identically distributed (iid) random effect for species, while the model = "generic0" argument is used for the phylogenetic random effect. The Cmatrix argument is used to specify the phylogenetic correlation matrix, which should be a precision matrix similar to MCMCglmm. We note that priors can be incorporated for parameter using the argument hyper=.

Code
time.inla <- system.time({
  model_inla <- inla(yi ~ x + f(species, model = "iid") + 
                       f(phylo, ## this needs to be a numeric to work
                         model = "generic0",
                         Cmatrix = phylo.prec.mat),
                     family = "gaussian",
                     data = dat)
})

fit_inla <- summary(model_inla)

Obtain the fixed effect estimates:

Code
coefs_inla <- as.data.frame(fit_inla$fixed)
coefs_inla
             mean   sd 0.025quant 0.5quant 0.975quant mode kld
(Intercept) 0.841 0.38      0.073     0.84      1.613 0.84   0
x           1.510 0.01      1.491     1.51      1.530 1.51   0

Obtain the random effect variance estimates. Note that INLA provides the inverse of the variance (precision) in their output.

Code
re_inla <- 1/fit_inla$hyperpar
sigma2_inla <- data.frame(
  model = "INLA",
  group = c( "Residual", "species", "phylo"),
  term = "var",
  estimate = re_inla$mean,
  std.error = fit_inla$hyperpar$sd,
  conf.low = re_inla$`0.025quant`,
  conf.high = re_inla$`0.975quant`
)

sigma2_inla
  model    group term estimate std.error conf.low conf.high
1  INLA Residual  var   0.2045     0.421   0.2435   0.17358
2  INLA  species  var   0.1177     4.134   0.3388   0.05315
3  INLA    phylo  var   0.1999     4.717   1.1547   0.05707

Additional note: if a model returns extreme or unreasonable variance estimates, it is important to check robustness by refitting the same model with another package. In INLA, centering the random effect estimates (by specifying const = TRUE within the random effect term) or trying higher starting values (default is 4, e.g. hyper = list(prec=list(initial=8))) to see if the estimates converge to more reasonable values. Random effect variance estimates are often unstable, so they should be interpreted with care.

Model estimates

Summary of model runtime, covariate \(x\) estimate and it’s confidence interval for each model:

Code
time.phyr <- as.numeric(time.phyr[3])
time.glmmTMB <- as.numeric(time.glmmTMB[3])
time.brms <- as.numeric(time.brms[3])
time.mcmc <- as.numeric(time.mcmc[3])
time.inla <- as.numeric(time.inla[3])


# combine fixed effect results 
res_fixed <- data.frame(
  model = c("phyr", "glmmTMB", "brms", "MCMCglmm", "INLA"),
  species_size = k.species,
  sample_size = n,
  run_time = c(time.phyr, time.glmmTMB, time.brms, time.mcmc, time.inla),
  b0 = rep(dat$b0[1], 5),
  b1 = rep(dat$b1[1], 5),
  mu = c(coefs_phyr$Value[2],
         coefs_tmb$Estimate[2], 
         coefs_brm$estimate[2], 
         coefs_mcmc$estimate[2], 
         coefs_inla$mean[2]),
  mu_ci_low = c(coefs_phyr$conf.low[2],
                coefs_tmb$`2.5 %`[2],
                coefs_brm$conf.low[2], 
                coefs_mcmc$conf.low[2], 
                coefs_inla$`0.025quant`[2]),
  mu_ci_high = c(coefs_phyr$conf.high[2],
                 coefs_tmb$`97.5 %`[2],
                 coefs_brm$conf.high[2], 
                 coefs_mcmc$conf.high[2], 
                 coefs_inla$`0.975quant`[2]),
  stringsAsFactors = FALSE
)
    
kable(res_fixed, 
  caption = "Runtime and fixed effect estimates of the simulated model",
  col.names = c("Model", "Species size", "Sample size", "Run time (s)", "b0", "b1", "Estimate (b1)", "CI low (b1)", "CI high (b1)"),
  digits = 3,
  format = "html"
)
Runtime and fixed effect estimates of the simulated model
Model Species size Sample size Run time (s) b0 b1 Estimate (b1) CI low (b1) CI high (b1)
phyr 30 300 0.36 1 1.5 1.51 1.491 1.53
glmmTMB 30 300 0.73 1 1.5 1.51 1.491 1.53
brms 30 300 387.10 1 1.5 1.51 1.491 1.53
MCMCglmm 30 300 50.09 1 1.5 1.51 1.490 1.53
INLA 30 300 3.16 1 1.5 1.51 1.491 1.53

Summary of variance component estimates for each model:

Code
# combine results together
s2 <- as.data.frame(rbind(sigma2_phyr,
                          sigma2_tmb,
                          sigma2_brms,
                          sigma2_mcmc, 
                          sigma2_inla))

# get subsets for each group
s2_phylo <- s2 %>% filter(group=="phylo")
s2_sp <- s2 %>% filter(group=="species")
s2_res <- s2 %>% filter(group=="Residual")


res_rand <- data.frame(
  model = c("phyr", "glmmTMB", "brms", "MCMCglmm", "INLA"),
  species_size = k.species,
  sample_size = n,
  run_time = c(time.phyr, time.glmmTMB, time.brms, time.mcmc, time.inla),
  sigma2_phylo = s2_phylo$estimate,
  sigma2_species = s2_sp$estimate,
  sigma2_residual = s2_res$estimate,
  stringsAsFactors = FALSE
)
    
kable(res_rand, 
  caption = "Runtime and random component variance estimates of the simulated model",
  col.names = c("Model", "Species size", "Sample size", "Run time (s)", "Phylo variance est.", "Non-phylo variance est.", "Residual variance est."),
  digits = 3,
  format = "html"
)
Runtime and random component variance estimates of the simulated model
Model Species size Sample size Run time (s) Phylo variance est. Non-phylo variance est. Residual variance est.
phyr 30 300 0.36 0.346 0.639 0.206
glmmTMB 30 300 0.73 0.132 0.427 0.206
brms 30 300 387.10 0.590 0.137 0.208
MCMCglmm 30 300 50.09 0.660 0.149 0.208
INLA 30 300 3.16 0.200 0.118 0.205

2.3 Extra analyses and notes

Sometimes we only have one measure per species. This may happen because of limited sampling or because repeated observations for a species have already been averaged. In such cases, it is common to work with a single value per species.

Here we will demonstrate how to fit a phylogenetic model when there is one measure per species. We will use the dataset dat of repeated measures per species simulated above (300 observations of 30 species) and compute a mean value for each species.

Code
dat.m <- dat |>
  group_by(species) |>
  summarise(
    x_mean   = mean(x, na.rm = TRUE),
    u.s_mean = mean(u.s, na.rm = TRUE),
    u.p_mean = mean(u.p, na.rm = TRUE),
    ei_mean  = mean(ei, na.rm = TRUE),
    yi_mean  = mean(yi, na.rm = TRUE),
    g = 1,
    .groups = "drop"
  )

head(dat.m)
# A tibble: 6 × 7
  species x_mean u.s_mean u.p_mean  ei_mean yi_mean     g
  <fct>    <dbl>    <dbl>    <dbl>    <dbl>   <dbl> <dbl>
1 1         15.1    0.210   0.181  -0.149      23.9     1
2 2         13.4   -0.200   0.622  -0.0260     21.4     1
3 3         15.9   -0.685  -0.484  -0.00467    23.7     1
4 4         14.7    0.494   0.0776  0.160      23.8     1
5 5         16.1    0.760  -0.247   0.328      26.0     1
6 6         14.2   -0.154   0.0875 -0.0629     22.1     1

So we now have a reduced dataset of 30 rows, with one value per species.

If we now try to fit the same phylogenetic GLMM as before, including both a random intercept for species and a phylogenetic effect:

Code
m <- glmmTMB(
  yi_mean ~ x_mean + (1|species) + propto(0 + species|g, phylo.mat),
  data = dat.m,
  REML = TRUE
)

# fixed effect estimates
as.data.frame(confint(m, parm="beta_"))
             2.5 % 97.5 % Estimate
(Intercept) -1.531  5.062    1.765
x_mean       1.233  1.663    1.448
Code
# random component estimates (on SD scale)
as.data.frame(confint(m, parm="theta_"))
                                 2.5 %     97.5 % Estimate
Std.Dev.(Intercept)|species 6.085e-259 1.213e+257   0.2717
Std.Dev.species1|g           3.512e-01  1.388e+00   0.6981
Code
# residual variance estimate
sigma(m)^2
[1] 0.07381

This model converged, but it returned very wide uncertainty intervals for the non-phylogenetic variance component (on the standard deviation scale). This reflects the fact that, with only one observation per species, the species intercept and the phylogenetic effect are not separately identifiable by the model. In some cases, the model may even fail to converge, highlighting the redundancy of including both terms.

Code
m <- glmmTMB(
  yi_mean ~ x_mean + propto(0 + species|g, phylo.mat),
  data = dat.m,
  REML = TRUE
)

# fixed effect estimates
as.data.frame(confint(m, parm="beta_"))
             2.5 % 97.5 % Estimate
(Intercept) -1.531  5.062    1.765
x_mean       1.233  1.663    1.448
Code
# random component estimates (on SD scale)
as.data.frame(confint(m, parm="theta_"))
                    2.5 % 97.5 % Estimate
Std.Dev.species1|g 0.3512  1.388   0.6981
Code
# residual variance estimate
sigma(m)^2
[1] 0.1476

When the non-phylogenetic component is removed, the estimate of the phylogenetic effect remains unchanged, the fixed effects are identical, and the residual variance increases to absorb the variability that can no longer be partitioned between the two random effects.

In some analyses, we may want to include a random slope for the phylogenetic effect. This allows us to ask whether the relationship between a covariate and the response varies among species in a way that reflects their shared evolutionary history. For example, we might be interested in whether species with different body weights show different slopes, or whether the effect of a treatment differs across species in a phylogenetically structured way.

Given the above simulated dataset, we assume a set of trait measures \(y_{ij}\) repeated measure (observation) \(i\) and for each species \(j\). The phylogenetic random slope model assuming independence is specified as follows:

\[ y_{ij} = \beta_0 + \beta_1 x_{ij} + n_j + p_{0j} + p_{1j}\,x_{ij} + \varepsilon_{ij} \]

Where:

  • \(p_{0} \sim \mathcal{N}(0, \sigma^2_{p0}\mathbf{A})\): phylogenetic random intercept
  • \(p_{1} \sim \mathcal{N}(0, \sigma^2_{p1}\mathbf{A})\): phylogenetic random slope, independent of \(p_{0}\)
Code
m.slope <- glmmTMB(yi ~ x + 
                     (1|species) + 
                     propto(0 + species|g, phylo.mat) +
                     propto(0 + x:species|g, phylo.mat),
                   data = dat,
                   REML = TRUE)

Then we can obtain the variance estimates:

Code
vc.slope <- VarCorr(m.slope) 
vc.slope$cond$species[1] #non-phylo variance
[1] 0.1411
Code
vc.slope$cond$g[1] #phylo intercept variance
[1] 0.149
Code
vc.slope$cond$g.1[1] #phylo slope variance
[1] 0.000741

What if there is a correlation between random intercept and slope?

glmmTMB cannot currently estimate correlated random intercepts and slopes when using the propto covariance structure. This means the intercept–slope covariance is fixed at zero and cannot be separated out. A common workaround is to centre the covariate, which reparameterises the model so that the intercept represents the expected response at the mean covariate value. This improves interpretability and typically stabilises slope variance estimates, though it does not recover any true intercept–slope correlation.

If the data contain little or no correlation, the variance estimates from glmmTMB with centred covariates will usually be close to those from packages that estimate the correlation. However, if the correlation is strong, glmmTMB may distort the partitioning of variance because the shared variation has no explicit covariance term.

For comparison, the random-effects structure in a model with correlated random intercepts and slopes is:

\[ \begin{bmatrix} \sigma^2_{\text{intercept}} & \sigma_{\text{intercept},\text{slope}} \\ \sigma_{\text{intercept},\text{slope}} & \sigma^2_{\text{slope}} \end{bmatrix} \]

while in glmmTMB with propto it is constrained to:

\[ \begin{bmatrix} \sigma^2_{\text{intercept}} & 0 \\ 0 & \sigma^2_{\text{slope}} \end{bmatrix} \]

Recommendation: fit models in both glmmTMB and in Bayesian frameworks such as the brms and MCMCglmm packages in R. Use globally centred covariates in both cases: centring helps stabilise estimation in glmmTMB and also improves interpretability in Bayesian models, though Bayesian approaches can additionally estimate the correlation directly.

  • If there is truly little or no correlation, the results will look very similar to glmmTMB: the variance estimates will be close, and the correlation will be near zero.

  • If there is strong correlation, the slope and intercept variance estimates in glmmTMB may still approximate the overall variability, but they could be biased, because part of the shared variation is forced into the variance components rather than partitioned as covariance.

Phylogenetic trees are always approximations and never represent the “true” evolutionary history with complete accuracy. In some cases, however, we may have access to multiple candidate trees. These can be used to fit separate models and then combine the results, for example using Rubin’s rules (Rubin, 1987), treating trees like imputations of the unknown phylogeny.

Here, we illustrate how to incorporate tree uncertainty with the simulated repeated-measures dataset. Using about 50 trees is often sufficient for high relative efficiency of the pooled estimates i.e., little further gain (Nakagawa & de Villemereuil, 2019).

As a first step, we generate 50 random phylogenetic trees to represent a set of hypothetical candidate trees. In practice, candidate trees can be obtained from different posterior distributions of phylogenetic trees using Bayesian inference of phylogenies.

Code
set.seed(123)

# 'k.species' and 'dat' are obtained from the 'Simulate data' section
# where dat$species is set as a factor => make sure to run this first.

# simulate 50 random trees 
trees <- replicate(50, ape::rtree(k.species, tip.label = seq_len(k.species)), simplify = FALSE)

# now make a phylogenetic correlation matrix for each tree,
make_phylo_mat <- function(tree, sp) {
  C <- vcv(tree, corr = TRUE)      
  C <- C[order(as.numeric(rownames(C))), order(as.numeric(rownames(C)))]
}

p.mats <- lapply(trees, make_phylo_mat, sp = sp.id)

Important note: the row rownames(C) and column names colnames(C) of the phylogenetic correlation matrix must match levels(dat$species), in the same order.

We fit the same model across 50 candidate trees:

Code
# function to fit PGLMM with different tree
fit_model <- function(Pmat) {
  glmmTMB(yi ~ x + (1|species) + propto(0 + species|g, Pmat),
                 data = dat, REML = TRUE)
}

# fit PGLMM model across all phylo correlation matrices
fits <- purrr::map(p.mats, fit_model)

Then using two packages mice and mitml we pool model estimates using Rubin’s rules.

First we get the pooled mice fixed effect estimates:

Code
### with mice package
library(mice)
summary(mice::pool(fits))
         term estimate std.error statistic    df    p.value
1 (Intercept)   0.9448   0.20966     4.507 286.5  9.610e-06
2           x   1.5109   0.01003   150.575 293.0 1.496e-279

By default, mice::pool uses the Barnard–Rubin small-sample adjustment (Barnard and Rubin, 1999) for degrees of freedom (df), which shrinks the df towards the complete-data df. Consequently, confidence intervals are slightly wider and p-values a little larger than under Rubin’s original (“old”) rule.

Now we get the pooled mitml fixed effect estimates:

Code
### with miml package
library(mitml)
fit.est <- mitml::testEstimates(fits, extra.pars=TRUE)
head(fit.est$estimates)
            Estimate Std.Error t.value         df     P(>|t|)        RIV
(Intercept)   0.9448   0.20966   4.507     123649 0.000006596 0.02031118
x             1.5109   0.01003 150.575 6393285759 0.000000000 0.00008755
                   FMI
(Intercept) 0.01992270
x           0.00008755

We obtain the same fixed effect estimates in both packages. However, mitml by default uses Rubin’s original degrees of freedom (“old rule”). This may be suitable if you deliberately want z-like inference.

If you wish to use mitml and obtain the fixed effect estimates inference using the Barnard–Rubin small-sample adjustment for degrees of freedom, you can obtain use the residual degrees of freedom from the models as a proxy for the complete-data df:

\[df.com \approx N−p\]

where \(N\) is the number of observations used and \(p\) is the number of conditional fixed-effect coefficients. Because we are fitting the same model across different phylogenetic matrices, df.com will be the same for all fits.

Code
# residual degrees of freedom of models
df.res <- vapply(fits, df.residual, numeric(1))
df.com <- unique(df.res) ## this should be a unique number, if not check your code for the model 

fit.est.com <- mitml::testEstimates(fits, extra.pars=TRUE, df.com=df.com)
head(fit.est.com$estimates)
            Estimate Std.Error t.value    df    P(>|t|)        RIV      FMI
(Intercept)   0.9448   0.20966   4.507 286.5 0.00000961 0.02031118 0.026677
x             1.5109   0.01003 150.575 293.0 0.00000000 0.00008755 0.006844

The output is then identical to the mice output.

We can obtain the pooled variance estimates of the random effects directly with the mitml package

Code
data.frame(
  sigma2.species = fit.est$extra.pars["Intercept~~Intercept|species",],
  sigma2.phylo = fit.est$extra.pars["species1~~species1|g",],
  sigma2.resid = fit.est$extra.pars["Residual~~Residual",]
)
  sigma2.species sigma2.phylo sigma2.resid
1         0.3575       0.0287        0.206

mitml provides estimates directly pooled on the variance scale.

3 Bayesian MCMC model runtime

Here we provide a breakdown of the compilation and sampling runtimes for the Bayesian MCMC models using the above simulated repeated measures dataset. The runtimes are provided for each model fitted using the MCMCglmm and brms packages. Note: the compilation time is the time taken to compile the model, while the sampling time is the time taken to sample from the posterior distribution of the model parameters.

First we set up the MCMCglmm model.

MCMCglmm

Set up MCMCglmm tuning parameters - usually set to some reasonably large values through trial and error.

Code
NITT <- 100000
BURNIN <- floor(0 * NITT)
THIN <- floor((NITT - BURNIN) / 1500)

Run a model that prepares the run but does not start actual sampling to have the baseline timing of the model pre-run protocols.

Code
runtime_1_pre <- benchmark(
    "process" = {
        model_mcmcglmm_pre <- MCMCglmm(yi ~ x,
                        random = ~species + phylo,
                        family = "gaussian",
                        ginverse = list(phylo = phylo.prec.mat),
                        prior = prior,
                        data = dat,
                        verbose = FALSE,
                        nitt = 1, burnin = 0, thin = 1
                        )
        }, replications = 1
)

Run full reasonable model (like above). Extract MCMC trace.

Code
THIN <- 1
model_mcmcglmm_max <- MCMCglmm(yi ~ x,
                        random = ~species + phylo,
                        family = "gaussian",
                        ginverse = list(phylo = phylo.prec.mat),
                        prior = prior,
                        data = dat,
                        verbose = FALSE,
                        nitt = NITT, burnin = BURNIN, thin = THIN
)
summary(model_mcmcglmm_max)

 Iterations = 1:100000
 Thinning interval  = 1
 Sample size  = 100000 

 DIC: 408.4 

 G-structure:  ~species

        post.mean     l-95% CI u-95% CI eff.samp
species     0.151 0.0000000692    0.301     3973

               ~phylo

      post.mean l-95% CI u-95% CI eff.samp
phylo     0.655   0.0137     1.62     2019

 R-structure:  ~units

      post.mean l-95% CI u-95% CI eff.samp
units     0.208    0.173    0.243    79192

 Location effects: yi ~ x 

            post.mean l-95% CI u-95% CI eff.samp    pMCMC    
(Intercept)     0.843   -0.141    1.796   100000    0.078 .  
x               1.510    1.490    1.530    98706 <0.00001 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Code
par_mcmcglmm_max <- model_mcmcglmm_max$VCV[, "species"]
plot(par_mcmcglmm_max)

Code
# geweke.plot(par_mcmcglmm_max)
# geweke.diag(par_mcmcglmm_max)
# heidel.diag(par_mcmcglmm_max)
test <- raftery.diag(par_mcmcglmm_max)

# update your run parameters
NITT <- test$resmatrix[,"N"] + test$resmatrix[,"M"]
THIN <- ceiling(test$resmatrix[,"N"] / test$resmatrix[,"Nmin"])
BURNIN <- test$resmatrix[,"M"]

runtime_1_run <- benchmark(
    "process" = {
        model_mcmcglmm_1_run <- MCMCglmm(yi ~ x,
                        random = ~species + phylo,
                        family = "gaussian",
                        ginverse = list(phylo = phylo.prec.mat),
                        prior = prior,
                        data = dat,
                        verbose = FALSE,
                        nitt = NITT, burnin = BURNIN, thin = THIN
                        )
        }, replications = 1
)

BRMS

“Reasonable” brms parameters.

Code
NITTb <- 10000
BURNINb <- 1000
THINb <- 1
CHAINS <- 1

Run a model that prepares the run but does not start actual sampling to have the baseline timing of the model pre-run protocols.

Code
runtime_2_pre <- benchmark(
    "process" = {
        model_brms_1_pre <- brm(yi ~ x + (1|species) + (1|gr(phylo, cov = phylo.mat)),
            data = dat,
            data2 = list(phylo.mat = phylo.mat),
            chains = CHAINS,
            iter = 2,
            warmup = 1,
            thin = 1
        )
    }, replications = 1
)

Run “larger” model and convert posterior to MCMC object.

Code
model_brms_max <- brm(yi ~ x + (1|species) + (1|gr(phylo, cov = phylo.mat)),
            data = dat,
            data2 = list(phylo.mat = phylo.mat),
            chains = CHAINS,
            iter = NITTb,
            warmup = BURNINb,
            thin = THINb
)

summary(model_brms_max)

par_brms_max <- as.mcmc(model_brms_max, pars = "sd_species__Intercept")[[1]]
plot(par_brms_max)

Code
test <- raftery.diag(par_brms_max)

# update your run parameters
NITTb <- test$resmatrix[,"N"] + test$resmatrix[,"M"]
THINb <- ceiling(test$resmatrix[,"N"] / test$resmatrix[,"Nmin"])
BURNINb <- test$resmatrix[,"M"]

runtime_2_run <- benchmark(
    "process" = {
        model_brms_1_run <- brm(yi ~ x + (1|species) + (1|gr(phylo, cov = phylo.mat)),
            data = dat,
            data2 = list(phylo.mat = phylo.mat),
            chains = CHAINS,
            iter = NITTb,
            warmup = BURNINb,
            thin = THINb
        )
    }, replications = 1
)

Summary runtimes

Summary table of runtimes for compilation and sampling:

Code
compil.perc.1 <- round(runtime_1_pre$elapsed / (runtime_1_pre$elapsed+runtime_1_run$elapsed) * 100, 1)
compil.perc.2 <- round(runtime_2_pre$elapsed / (runtime_2_pre$elapsed+runtime_2_run$elapsed) * 100, 1)
sampl.perc.1 <- round(runtime_1_run$elapsed / (runtime_1_pre$elapsed+runtime_1_run$elapsed) * 100, 1)
sampl.perc.2 <- round(runtime_2_run$elapsed / (runtime_2_pre$elapsed+runtime_2_run$elapsed) * 100, 1)

time.summary <- data.frame(
  model = c("MCMCglmm", "brms"),
  compilation.time = c(runtime_1_pre$elapsed, runtime_2_pre$elapsed),
  perc = c(compil.perc.1, compil.perc.2), 
  sampling.time = c(runtime_1_run$elapsed - runtime_1_pre$elapsed, runtime_2_run$elapsed - runtime_2_pre$elapsed),
  perc = c(sampl.perc.1, sampl.perc.2)
)

kable(time.summary)
model compilation.time perc sampling.time perc.1
MCMCglmm 0.03 0.3 9.97 99.7
brms 63.42 45.7 12.04 54.3

4 Case studies

4.1 Background

The following case studies illustrate how phylogenetic mixed models can be applied to diverse questions in ecology and evolution. The first examines patterns of plumage colour in birds, while the second explores macroevolutionary patterns in plant traits. Together, they demonstrate the flexibility of these methods across taxa and research questions.

All models, results, and datasets presented in these case studies are intended for illustrative purposes only. They are designed to demonstrate analytical approaches rather than to provide definitive biological insights. No substantive conclusions should be drawn from these analyses.

4.2 Case study 1: Bird color evolution

Birds are a valuable system for studying ecological and evolutionary processes because their diversity in form, behaviour, and coloration is well documented across many species and habitats. Variation in plumage colour, in particular, can provide insights into mechanisms such as sexual selection, camouflage, and signalling. By examining these traits, researchers can better understand how environmental and evolutionary pressures shape biodiversity.

credits: Andy Chilton, Boris Smokrovic, David Clode, Jaime Spaniol, Joshua J. Cotte, Vincent Van Zalinge / unsplash.com.

Data overview

Load data bird spectrum data:

Code
# Load bird spectrum data 
bird_data <- read_delim("data/Spec_IndivReg_Coralie.csv", 
    delim = ";", escape_double = FALSE, locale = locale(decimal_mark = ","), 
    trim_ws = TRUE)

# summary of birds species and genus
length(table(bird_data$genus_original)) # 446 genus
[1] 446
Code
length(table(bird_data$sci_name_Jetz)) # 949 species
[1] 949
Code
#length(table(bird_data$sci_name_original)) # 952 original species

# Remove the specified species from bird_data
bird_data <- bird_data |> 
  filter(!sci_name_Jetz %in% c("Basileuterus_rufifrons", "Malurus_lamberti", "Malurus_splendens"))


########## Notes #########

# missing values ---> not sure why?
#na_count <- colSums(is.na(dat2))
#na_count[na_count > 0]

# individuals a-c are male and d-f are female
#table(bird_data$sex, bird_data$individual)

# number of measurements?
#table(bird_data$Nmeasured)

# duplicates per individual per body region
#dup <- dat |>
#    summarise(n = n(), 
#              .by = c(wl, individual_nonrep, sex, body_region))
#r <- dup[which(dup$n>1),]
#table(r$individual_nonrep)

Some notes:

  • The dataset contains data for 949 bird species, with 446 unique genera.

  • Spectral values are normalised reflectance data.

  • Nmeasured is the number of measurements per body patch.

  • Each body region measured 5 times (then averaged).

  • These species seem to have two measurements per body region per individual, which we remove to facilitate the analysis.:

    Basileuterus_rufifrons, Malurus_lamberti, Malurus_splendens

Color data set-up

Obtain wavelength dataset

Now we want to create a wavelength dataset using the pavo package given the spectral reflectance data.

Code
# set up wavelength dataset (wavelengths columns 300 to 474)
dat <- bird_data |> 
  pivot_longer(cols = `300`:`700`, names_to="wl", values_to="refl") |> 
  dplyr::select(individual_nonrep, body_region, sex, wl, refl) |> 
  mutate(wl = as.numeric(wl))

# pivot so each column is an individual body region measurement
dat2 <- dat |> 
  pivot_wider(names_from = c("individual_nonrep", "sex", "body_region"),
              values_from = "refl", names_sep = ".")

# create spectral dataset with pavo
specs <- as.rspec(dat2)

# some examples of individual birds body region color spectrum
plot(Acrocephalus_palustris_a.Male.throat ~ wl, type="l", data=specs, title="Acrocephalus palustris (throat)")

Code
plot(Alle_alle_a.Male.throat ~ wl, type="l", data=specs, title="Alle alle (throat)")

Code
plot(Aplonis_metallica_a.Male.wing_cov ~ wl, type = "l", data = specs, title="Aplonis metallica (wing covert)")

Code
# use procspec to adjust negative values by shifting them by 10
# (this maybe due to darker colors)
specs <- procspec(specs, fixneg="addmin")
plot(specs, select = 10)

Obtain spectral shape descriptors

Using the wavelength dataset we can now obtain spectral shape descriptors. These descriptors will be used in the model. Here we will focus on four descriptors of interest: brightness (B1), spectral slope (S1), spectral curvature (S9), and hue (H4). More information about the spectral shape descriptors can be found here: https://book.colrverse.com/spectral-shape-descriptors.html

Code
# Obtain spectral shape descriptors
spec.des <- summary(specs, subset = c("B1", "B2", "S9", "H4")) ## using subset makes it faster to run by selecting the shapes of interest

dev.off()
null device 
          1 
Code
# distribution of B1
ggplot(spec.des, aes(x = B1)) +
  geom_histogram(bins = 30, colour = "black", fill = "grey") +
  labs(x = "B1", title = "B1: Total brightness") +
  theme_bw()

# distribution of S9
ggplot(spec.des, aes(x = S9)) +
  geom_histogram(bins = 30, colour = "black", fill = "grey") +
  labs(x = "S9", title = "S9: Carotenoid chroma") +
  theme_bw()

# vdistribution o fH4
ggplot(spec.des, aes(x = H4)) +
  geom_histogram(bins = 30, colour = "black", fill = "grey") +
  labs(x = "H4", title = "H4: Hue (segment classification)") +
  theme_bw()

The first dataset is the shape descriptors dataset, which we will use to model the continuous trait (brightness).

Code
spec.des$rowname <- rownames(spec.des)

spec.dat <- spec.des |> 
  mutate(sex = case_when(
    grepl("Male", rowname) ~ "male",
    grepl("Female", rowname) ~ "female"),
    species = gsub("\\_[a-f]\\..*$", "", rowname),
    body_region = str_extract(rowname, "[a-z]+$")
  ) 

write.csv(spec.dat, file="data/spec_data_for_model.csv")

Obtain carotenoid datasets: binary and ordinal traits

We will use the carotenoid dataset to model the presence/absence of carotenoid coloration in birds. This dataset is based on the spectral reflectance data and the spectral shape descriptors.

Let’s set up the dataset for modelling a binary trait (absence/presence of carotenoid color):

Code
# 1) get human visual model (CIE 10 degree observed under D65 "day light")
vm <- vismodel(specs, visual = "cie10", illum = "D65", bkg = "ideal", relative = FALSE)

# 2) convert to CIELAB colorspace (to get hue and chroma)
lab <- colspace(vm, space = "cielab") 

# 3) get chroma and hue angle (converting CIELAB to CIELCh)
L <- lab$L
a <- lab$a
b <- lab$b
C <- sqrt(a^2 + b^2)
h <- (atan2(b, a) * 180 / pi) %% 360  # degrees in 0 to 360

# 4) thresholds for carotenoid range and saturation
h_lower <- 330   # start of red
h_upper <- 100   # end of yellow
C_min   <- 15 # min chroma
L_min   <- 20 # avoid very dark samples

# 5) Hue range test 
in_range <- h >= h_lower | h <= h_upper

# 6) COmpute binary trait:  1 = carotenoid like colour present, 0 = absent
present <- as.integer(in_range & C >= C_min & L >= L_min)

# set up dataset
carot.dat.all <- data.frame(
  rowname  = rownames(lab),
  L = L, a = a, b = b, C = C, h = h,
  carotenoid = present
)

# merge with spec.data based on "rowname" column
carot.dat.all <- merge(spec.dat, carot.dat.all, by.x = "rowname", by.y = "rowname", all = TRUE)
# create individual id variable
carot.dat.all$indiv_rep <- sub(".*_([a-f])\\..*$", "\\1", carot.dat.all$rowname)

# number of observations with carotenoid like colour
table(carot.dat.all$carotenoid)

    0     1 
33520   506 
Code
# # checks
# carot.dat.all |>
#   filter(L>20 & C>12 & in_range) |>
#   arrange(desc(L))

# #  check bird cardinalis cardinalis (should be yellow or red?)
# carot.dat.all |> 
#   filter(grepl("Cardinalis_cardinalis", rowname)) |> 
#   arrange(desc(h))


# Plot
ggplot(carot.dat.all, aes(h, C)) +
  geom_point(data = subset(carot.dat.all, carotenoid == 0),
             shape = 21, size = 1.5, fill = "grey85", colour = "grey70", alpha = 0.6) +
  geom_point(data = subset(carot.dat.all, carotenoid == 1),
             aes(fill = L, colour = L), shape = 21, size = 1.8, stroke = 0.4, alpha = 0.95) +
  scale_fill_gradient(name = "L*", limits = c(15, 50), low = "darkred", high = "lightcoral") +
  scale_colour_gradient(guide = "none", limits = c(15, 50), low = "darkred", high = "lightcoral") +
  labs(x = "Hue (degrees)", y = "Chroma (C*)", title = "Carotenoid presence") +
  theme_bw()

Let’s save the dataset for modelling later on:

Code
carot.dat <- carot.dat.all

# save as csv
write.csv(carot.dat, file="data/carotenoid_data_for_model.csv", row.names = FALSE)

Now let’s obtain the dataset where we summarise for each individual bird the proportion of body region with carotenoid color presence (ordinal data trait), and save it for modelling later on:

Code
carot.ordinal <- carot.dat.all |>
  group_by(species, sex, indiv_rep) |>
  summarise(prop_carotenoid = mean(carotenoid), .groups = "drop")

# save as csv
write.csv(carot.ordinal, file="data/ordinal_data_for_model.csv", row.names = FALSE)

Phylogenetic correlation matrix set-up

Load and view phylogenetic tree:

Code
# Load bird tree (consensus tree = "combined tree")
bird.tree <- read.tree("data/Stage2_Hackett_MCC_no_neg.tre")

### Prune bird tree
bird.pruned <- keep.tip(bird.tree, bird_data$sci_name_Jetz)
# check whether names match in data and tree
check <- name.check(bird.pruned, bird_data$sci_name_Jetz, sort(bird.pruned$tip.label))

# plot tree
plotTree(bird.pruned, ftype="i", fsize=0.4, lwd=1, type="fan")

Code
dev.off()
null device 
          1 

Set up correlation matrix for glmmTMB model and check it corresponds to the species labels in the data:

Code
# set up phylogenetic correlation matrix
phylo.mat <- vcv(bird.pruned, corr = TRUE) 
phylo.mat <- phylo.mat[sort(rownames(phylo.mat)), sort(rownames(phylo.mat))]
saveRDS(phylo.mat, file = "data/phylo_matrix.rds")


# checks   
# length(colnames(phylo.mat))==length(table(spec.dat$species))
# all(head(rownames(phylo.mat))==head(colnames(phylo.mat)))
# head(table(spec.dat$species))

Model 1. Continuous trait

Code
# load data
spec.dat <- read_csv("data/spec_data_for_model.csv")
phylo.mat <- readRDS("data/phylo_matrix.rds")

# load library                                 
library(glmmTMB)

# add grouping variable (set it to 1) - this is necessary to fit the glmmTMB model
spec.dat$g <- 1
Modelling total brightness (B1)

The brightness trait is right-skewed (as shown above), which is consistent with multiplicative evolutionary change. To identify an appropriate sampling distribution, we will fit four models with an identical linear predictor and random effects structure:

  1. Gaussian to model \(\log(B1)\)
  2. Gamma with a log link to model \(B1\)

For each model we will examine simulated standardised residuals using to assess nonlinearity and heteroscedasticity. If two or more models perform similarly, we will prefer the model with clearer interpretation on the original scale.

Code
# Fit models --------------

# normal
time_norm <- system.time(
  m1 <- glmmTMB(log(B1) ~ body_region * sex + (1|species) + propto(0 + species|g,phylo.mat),
                      family = gaussian(),
                      data = spec.dat) 
  )

# Gamma distribution
time_gamma <- system.time(
  m2 <- glmmTMB(B1 ~ body_region * sex + (1|species) + propto(0 + species|g,phylo.mat),
                      family = Gamma(link = "log"),
                      data = spec.dat)
)

# Get model info  ---------------------------
# check whether model has postive definite hessian

b1_output <- data.frame(
  model = c("Gaussian (log)", "Gamma"),
  convergence = c(m1$sdr$pdHess, m2$sdr$pdHess),
  runtime = c(time_norm[["elapsed"]], time_gamma[["elapsed"]])
)

b1_output
           model convergence runtime
1 Gaussian (log)        TRUE   92.36
2          Gamma        TRUE  103.35
Model diagnostics

Let’s check residual plots with the DHARMa packages. First, the log(B1) assuming normal distribution residual checks:

Code
res_gauss <- DHARMa::simulateResiduals(fittedModel = m1)
plot(res_gauss)

The model checks assuming Gamma distribution and log link function:

Code
res_gamma <- DHARMa::simulateResiduals(fittedModel = m2)
plot(res_gamma)

We found that the Gamma distribution shows improve model fit in the residual plots.

Model estimates

Let’s obtain the estimate of the phylogenetic signal and non-phylogenetic signal for the Gamma model:

Code
# get random effect component estimates on SD-scale 
m2_re <- as.data.frame(confint(m2, parm="theta_"))
sigma2_s <- m2_re$Estimate[1]^2 # non-phylogenetic variance
sigma2_p <- m2_re$Estimate[2]^2 # phylogenetic variance estimate

p.signal <- sigma2_p / (sigma2_p + sigma2_s)
p.signal
[1] 0.842
Code
np.signal <- 1-p.signal
np.signal
[1] 0.158

On the log mean scale of the Gamma model, the phylogenetic species effect explained 84.2% of the total species level random effect variance i.e. this represents the degree of phylogenetic signal in the overall variance sourced from species. The non-phylogenetic effect explained 15.8% of the total species level random effect variance.

We can obtain and compare the residual variances for each model with the following:

Code
# residual variance of gaussian model
m1_res.var <- sigma(m1)^2

# residual variance of gamma model
phi <- sigma(m2)^2 #phi given on SD-scale
scale <- 1/phi #derive scale parameter
m2_res.var <- trigamma(scale)

# print
data.frame(
  model = c("Gaussian (log)", "Gamma"),
  residual_variance = c(m1_res.var, m2_res.var)
)
           model residual_variance
1 Gaussian (log)            0.3265
2          Gamma            0.3319

To assess differences in total brightness between sexes for each body region, we compute marginal means from the fitted model and perform pairwise comparisons between females and males. The resulting ratios (female/male) and their confidence intervals are then plotted to visualise the magnitude and direction of differences across body regions.

Code
emm_b1 <- emmeans(m2, ~ sex | body_region, type = "response")

# get contrasts (ratios) back transformed on response scale with CI
b1_sex_diff <- contrast(emm_b1, method = "pairwise", reverse=TRUE) |> 
  summary(infer = TRUE, type = "response")

b1_sex_diff
body_region = back:
 contrast      ratio     SE  df asymp.LCL asymp.UCL null z.ratio p.value
 female / male 0.973 0.0139 Inf     0.946     1.000    1  -1.923  0.0545

body_region = belly:
 contrast      ratio     SE  df asymp.LCL asymp.UCL null z.ratio p.value
 female / male 1.069 0.0153 Inf     1.040     1.100    1   4.708  <.0001

body_region = cov:
 contrast      ratio     SE  df asymp.LCL asymp.UCL null z.ratio p.value
 female / male 0.998 0.0143 Inf     0.970     1.026    1  -0.141  0.8882

body_region = crown:
 contrast      ratio     SE  df asymp.LCL asymp.UCL null z.ratio p.value
 female / male 0.912 0.0131 Inf     0.887     0.938    1  -6.390  <.0001

body_region = tail:
 contrast      ratio     SE  df asymp.LCL asymp.UCL null z.ratio p.value
 female / male 1.020 0.0145 Inf     0.992     1.050    1   1.427  0.1537

body_region = throat:
 contrast      ratio     SE  df asymp.LCL asymp.UCL null z.ratio p.value
 female / male 1.075 0.0154 Inf     1.046     1.106    1   5.099  <.0001

Confidence level used: 0.95 
Intervals are back-transformed from the log scale 
Tests are performed on the log scale 
Code
## plot pairwise differences between female and male total brightness
b1_sex_diff |>
  arrange(ratio) |>
  mutate(
    body_region = factor(body_region, unique(body_region), ordered = TRUE)) |>
  ggplot(aes(y = body_region, x = ratio)) +
  geom_point(size = 3, colour = "#7B5EA9") + 
  geom_errorbar(aes(xmin = asymp.LCL, xmax = asymp.UCL), 
                width = 0.2, colour = "#7B5EA9") +
  geom_vline(xintercept = 1, linetype = "dashed", colour = "grey40") +
  labs(y = "Body Region", x = "Female / Male Ratio", 
       title = "Brightness") +
  theme_bw() +
  theme(legend.position = "none")

Ratios \(>1\) indicate greater brightness in females, while ratios \(<1\) indicate greater brightness in males.

Model 2. Binary trait

Binary colour traits, such as the presence of carotenoid colours, may be associated with distinct evolutionary and ecological drivers.

Here we want to model the absence or presence of carotenoid across all body regions accounting for sex and including species- and phylogeny-level random effects. We will use the carotenoid dataset which we obtained earlier.

Modelling carotenoid presence

We will fit two models: - Binomial model with a logit link function - Beta binomial model with a logit link function

Code
# Fit models --------------

# load dat
carot.dat <- read_csv("data/carotenoid_data_for_model.csv")
carot.dat$g <- 1 
 
# binomial model
time_binom <- system.time(
  m3 <- glmmTMB(carotenoid ~ body_region * sex + (1|species) + propto(0 + species|g,phylo.mat),
                family = binomial(link = "logit"),
                data = carot.dat)
)

# beta binomial
time_bbinom <- system.time(
  m4 <- glmmTMB(carotenoid ~ body_region * sex + (1|species) + propto(0 + species|g,phylo.mat),
                family = betabinomial(link = "logit"),
                data = carot.dat)
)

# Get model info -----------

carotmod_output <- data.frame(
  model = c("Binomial", "Beta binomial"),
  convergence = c(m3$sdr$pdHess, m4$sdr$pdHess),
  runtime = c(time_binom[["elapsed"]], time_bbinom[["elapsed"]]),
  AIC = c(AIC(m3), AIC(m4))
)
carotmod_output 
          model convergence runtime  AIC
1      Binomial        TRUE   72.56 3094
2 Beta binomial        TRUE  223.50 3096
Model diagnostics

Let’s check residual plots with the DHARMa packages. First, let’s get the residual plots for the binomial model:

Code
res_binom <- DHARMa::simulateResiduals(fittedModel = m3)
plot(res_binom)

Now the model checks assuming zero inflated binomial distribution and log link function:

Code
res_bbinom <- DHARMa::simulateResiduals(fittedModel = m4)
plot(res_bbinom)

We found that the binomial model has improved model fit in AIC and in the residual plots.

Model estimates

Let’s obtain the estimate of the phylogenetic signal for this model:

Code
# get random effect component estimates on SD-scale
m3_re <- as.data.frame(confint(m3, parm="theta_"))

sigma2_s <- m3_re$Estimate[1]^2 # non-phylogenetic variance
sigma2_p <- m3_re$Estimate[2]^2 # phylogenetic variance estimate

p.signal <- sigma2_p / (sigma2_p + sigma2_s)
p.signal
[1] 0.9243

Get model estimated marginals means on the response scale:

Code
# Estimated marginal means on the response scale (odds)
emm_m3 <- emmeans(m3, ~ sex | body_region, type = "response")

# get contrasts (odds ratios)
m3_sex_prob <- contrast(emm_m3, method = "pairwise", reverse=TRUE) |> 
  summary(infer = TRUE, type = "response")

# Put into data frame for plotting
sex_prob_df <- as.data.frame(m3_sex_prob) |>
  rename(ratio = odds.ratio, lower.CL = asymp.LCL, upper.CL = asymp.UCL)
sex_prob_df 
body_region = back:
 contrast       ratio      SE  df lower.CL upper.CL null z.ratio p.value
 female / male 0.0000 0.00005 Inf   0.0000      Inf    1  -0.007  0.9947

body_region = belly:
 contrast       ratio      SE  df lower.CL upper.CL null z.ratio p.value
 female / male 0.9353 0.13585 Inf   0.7036        1    1  -0.460  0.6453

body_region = cov:
 contrast       ratio      SE  df lower.CL upper.CL null z.ratio p.value
 female / male 0.4490 0.21091 Inf   0.1788        1    1  -1.705  0.0883

body_region = crown:
 contrast       ratio      SE  df lower.CL upper.CL null z.ratio p.value
 female / male 0.7303 0.24013 Inf   0.3834        1    1  -0.956  0.3391

body_region = tail:
 contrast       ratio      SE  df lower.CL upper.CL null z.ratio p.value
 female / male 0.5335 0.27658 Inf   0.1931        1    1  -1.212  0.2255

body_region = throat:
 contrast       ratio      SE  df lower.CL upper.CL null z.ratio p.value
 female / male 0.7066 0.18028 Inf   0.4285        1    1  -1.361  0.1734

Confidence level used: 0.95 
Intervals are back-transformed from the log odds ratio scale 
Tests are performed on the log odds ratio scale 
Code
# Plot
sex_prob_df |>
  arrange(ratio) |>
  filter(!(body_region=="back")) |>
  mutate(body_region = factor(body_region, unique(body_region), ordered = TRUE)) |>
  ggplot(aes(y = body_region, x = ratio, colour = body_region)) +
  geom_point(size = 3, colour = "#4B6EA5") + 
  geom_errorbar(aes(xmin = lower.CL, xmax = upper.CL), 
                width = 0.2, colour = "#4B6EA5") +
  geom_vline(xintercept = 1, linetype = "dashed", colour = "grey40") +
  labs(y = "Body Region", x = "Female / Male Odds Ratio", 
       title = "Sex differences in carotenoid presence") +
  theme_bw() +
  theme(legend.position = "none")

Model 3. Ordinal trait

The ordinal trait is the percentage of body region with carotenoid presence. We will fit a beta-binomial and model to this trait, which is suitable for modeling proportions.

Modelling carotenoid proportion per body region
Code
# load data
ord.dat <- read_csv("data/ordinal_data_for_model.csv")
ord.dat$g <- 1 # add grouping variable 

# fit model 
time_ord <- system.time(
  m5 <- glmmTMB(prop_carotenoid ~ sex + (1|species) + propto(0 + species|g,phylo.mat),
                  family = ordbeta(),
                  data = ord.dat)
)

# output
data.frame(
  model = "Ordinal beta",
  convergence = m5$sdr$pdHess,
  runtime = time_ord[["elapsed"]],
  AIC = AIC(m5)
)
         model convergence runtime   AIC
1 Ordinal beta        TRUE   55.25 764.1
Model diagnostics

Look at residual diagnostic plots:

Code
res_ord <- DHARMa::simulateResiduals(fittedModel = m5)
plot(res_ord)

Model estimates

Phylogenetic signal:

Code
# get random effect component estimates on SD-scale
m5_re <- as.data.frame(confint(m5, parm="theta_"))

sigma2_s <- m5_re$Estimate[1]^2 # non-phylogenetic variance est.
sigma2_p <- m5_re$Estimate[2]^2 # phylogenetic variance est.

p.signal.m5 <- sigma2_p / (sigma2_p + sigma2_s)
p.signal.m5
[1] 0.9666

Now look at the difference in the proportion of carotenoid colour between females and males from the ordinal beta model (m5), and plot the model-based estimate with its 95% confidence interval on the response scale.

Code
emm_m5 <- emmeans(m5, ~ sex, type = "response")

# pairwise contrast: Female vs Male
m5_sex_OR <- contrast(emm_m5, method = "pairwise") |>
  summary(infer = TRUE, type = "response")

# get summary with CI
sex_OR <- as.data.frame(m5_sex_OR) |>
  rename(OR = odds.ratio, lower.CL = asymp.LCL, upper.CL = asymp.UCL)

sex_OR
 contrast          OR     SE  df lower.CL upper.CL null z.ratio p.value
 female / male 0.9169 0.0246 Inf   0.8699   0.9664    1  -3.235  0.0012

Confidence level used: 0.95 
Intervals are back-transformed from the log odds ratio scale 
Tests are performed on the log odds ratio scale 

4.3 Case study 2: Evolution of plant hydraulic traits

We re-analysed the published study of Sanchez-Martinez et al. (2020) on the evolution of plant hydraulic traits using phylogenetic generalized linear mixed models (PGLMMs). The original study used a Bayesian MCMC approach to fit the models with the MCMCglmm package. Here we will use the glmmTMB package to fit the models with different sampling distributions and compare with MCMCglmm. Again all results are for illustrative purpose only and we do not intend to infer any biological or ecological conclusions from the following results.

credits: Chanya_B / stock.adobe.com

Data overview

Code
# Load plant hydraulic traits dataset
hydra.dat <- read_csv("data/HydraEvol2020.csv")

# Have a look at distribution of traits
hist(hydra.dat$Ks, breaks = 50, main = "Distribution of Ks", xlab = "Ks")

Code
boxplot(hydra.dat$Ks ~ hydra.dat$group, main = "Boxplot of Ks by group", xlab = "Group", ylab = "Ks")

Code
hist(hydra.dat$P50, breaks = 50, main = "Distribution of P50", xlab = "P50")

Code
boxplot(hydra.dat$P50 ~ hydra.dat$group, main = "Boxplot of P50 by group", xlab = "Group", ylab = "P50")

Phylogenetic tree

Code
# Load tree 
plant.tree <- ape::read.tree("data/genus-level_phylogeny.tre")

# plot tree
plotTree(plant.tree, ftype="i", fsize=0.4, lwd=1, type="fan")

Code
dev.off()
null device 
          1 

1. Model for kS

Plant species with high saturated hydraulic conductivity (kS) are able to transport water through their xylem more efficiently, and are therefore characterised as highly efficient in water transport.

First let’s set up the models for glmmTMB:

  • Log(response) Gaussian.

  • Gamma model.

First, let’s set up the phylogenetic correlation matrix for the glmmTMB model and the inverse matrix for MCMCglmm.

We want to obtain a phylogenetic matrix that match all genera in the Ks dataset.m We will therefore remove all missing entries for the Ks trait and prune the tree and the dataset to have the same genera in both.

Code
# create dat for ks (remove all missing values)
ks.dat <- subset(hydra.dat, !is.na(Ks))
all(is.na(ks.dat$genus))
[1] FALSE
Code
# get common genus dataset and tree
common.genus <- intersect(plant.tree$tip.label, ks.dat$genus)

# Prune tree
plant.tree.pruned <- ape::drop.tip(plant.tree, setdiff(plant.tree$tip.label, common.genus))
#length(plant.tree.pruned$tip.label)

# Prune dataset
ks.dat <- ks.dat[ks.dat$genus %in% common.genus, ]
#length(table(ks.dat$genus))

# check whether names match in data and tree
check <- geiger::name.check(plant.tree.pruned, ks.dat$genus, sort(plant.tree.pruned$tip.label))

# set up phylogenetic correlation matrix
phylo.mat.p <- vcv(plant.tree.pruned, corr = TRUE) 
phylo.mat.p <- phylo.mat.p[sort(rownames(phylo.mat.p)), sort(rownames(phylo.mat.p))]

# set up inverse phylogenetic correlation matrix for MCMCglmm
phylo.inv <- MCMCglmm::inverseA(plant.tree.pruned, nodes = "TIPS")$Ainv
phylo.inv <- phylo.inv[sort(rownames(phylo.inv)),]

# checks   
# length(colnames(phylo.mat.p))==length(table(ks.dat$genus))
# all(head(rownames(phylo.mat.p))==head(colnames(phylo.mat.p)))
# length(rownames(phylo.inv))==length(table(ks.dat$genus))
# head(table(ks.dat$genus))
Code
# make sure to add grouping factor for glmmTMB
ks.dat$g <- 1
ks.dat$genus <- as.factor(ks.dat$genus)


# Fit models --------------

# normal
time_norm <- system.time(
  m6 <- glmmTMB(log(Ks) ~ group + (1|genus) + propto(0 + genus|g, phylo.mat.p),
                      family = gaussian(),
                      REML=TRUE,
                      data = ks.dat)
  )

# Gamma distribution
time_gamma <- system.time(
  m7 <- glmmTMB(Ks ~ group + (1|genus) + propto(0 + genus|g,phylo.mat.p),
                      family = Gamma(link = "log"),
                      data = ks.dat)
)

Now, we will fit the Gaussian Log(Ks) model with MCMCglmm:

Diagnostic plots

Let’s check residual plots with the DHARMa packages. First, the log(Ks) assuming normal distribution residual checks:

Code
res_norm <- DHARMa::simulateResiduals(fittedModel = m6)
plot(res_norm)

The model checks assuming Gamma distribution and log link function:

Code
res_gamma2 <- DHARMa::simulateResiduals(fittedModel = m7)
plot(res_gamma2)

Residual diagnostics are relatively similar.

Results

Get phylogenetic signal from glmmTMB Gaussian model:

Code
# get random effect component estimates on SD-scale 
m6_re <- as.data.frame(confint(m6, parm="theta_"))
sigma2_s <- m6_re$Estimate[1]^2 # non-phylogenetic variance
sigma2_p <- m6_re$Estimate[2]^2 # phylogenetic variance estimate

p.signal <- sigma2_p / (sigma2_p + sigma2_s)
p.signal
[1] 0.8391

We found that the phylogenetic species effect explained 83.9% of the total species level random effect variance, and hence the non-phylogenetic effect explained only 16.1% of the total species level random effect variance.

Get model estimated marginals means on the response scale:

Code
# Estimated marginal means on the response scale (odds)
emm_m6 <- emmeans(m6, ~ group, type = "response")
emm_m6
 group       response    SE   df lower.CL upper.CL
 Angiosperms     1.22 0.938 1021    0.271     5.51
 Gymnosperms     0.62 0.307 1021    0.235     1.64

Confidence level used: 0.95 
Intervals are back-transformed from the log scale 
Code
# Get the contrast between the two groups
group_diff <- contrast(emm_m6, method = "pairwise", reverse=TRUE) |> 
  summary(infer = TRUE, type = "response")


# Plot
ggplot(group_diff, aes(y = contrast, x = ratio)) +
  geom_point(size = 3, colour = "#6BAF92") +
  geom_errorbar(aes(xmin = lower.CL, xmax = upper.CL), 
                width = 0.2, colour = "#6BAF92") +
  geom_vline(xintercept = 1, linetype = "dashed", colour = "grey40") +
  labs(y = NULL, x = "",
       title = "kS contrast: Angiosperms vs Gymnosperms") +
  theme_bw() +
  theme(legend.position = "none")

2. Model for P50

P50 represents the level of water stress at which a tree experiences a 50% loss of hydraulic conductivity. More negative P50 values indicate that trees can withstand greater hydraulic stress before suffering hydraulic damage, so communities with lower P50s are considered more resilient to increasing water stress (Trugman et al., 2020).

First let’s set up the models for glmmTMB:

  • Try gamma model

  • Log(response) gaussian

First, le’s a phylogenetic matrix that match all genera in the P50 dataset. We will therefore remove all missing entries for the Ks trait and prune the tree and the dataset to have the same genera in both.

Code
# create dat for ks (remove all missing values)
p50.dat <- subset(hydra.dat, !is.na(P50))

# create negative P50 variable
p50.dat$negP50 <- - p50.dat$P50

# get common genus across dataset and tree
common.genus <- intersect(plant.tree$tip.label, p50.dat$genus)

# Prune dataset
p50.dat <- p50.dat[p50.dat$genus %in% common.genus, ]

# Prune tree
plant.tree.pruned <- ape::drop.tip(plant.tree, setdiff(plant.tree$tip.label, common.genus))

# check whether names match in data and tree
check <- geiger::name.check(plant.tree.pruned, p50.dat$genus, sort(plant.tree.pruned$tip.label))

# set up phylogenetic correlation matrix
phylo.mat.p <- vcv(plant.tree.pruned, corr = TRUE) 
phylo.mat.p <- phylo.mat.p[sort(rownames(phylo.mat.p)), sort(rownames(phylo.mat.p))]

# set up inverse phylogenetic correlation matrix for MCMCglmm
phylo.mat.p.inv <- solve(phylo.mat.p)


# checks   
# length(colnames(phylo.mat.p))==length(table(p50.dat$genus))
# all(head(rownames(phylo.mat.p))==head(colnames(phylo.mat.p)))
# head(table(p50.dat$genus))
Code
# make sure to add grouping factor for glmmTMB
p50.dat$g <- 1
p50.dat$genus <- as.factor(p50.dat$genus)


# Fit models --------------

# normal
time_norm <- system.time(
  m8 <- glmmTMB(log(negP50) ~ group + (1|genus) + propto(0 + genus|g, phylo.mat.p),
                      family = gaussian(),
                      REML=TRUE,
                      data = p50.dat)
  )

# Gamma distribution
time_gamma <- system.time(
  m9 <- glmmTMB(negP50 ~ group + (1|genus) + propto(0 + genus|g,phylo.mat.p),
                      family = Gamma(link = "log"),
                      data = p50.dat)
)

Same models with MCMCglmm

Diagnostic plots

Let’s check residual plots with the DHARMa packages. First, the log(Ks) assuming normal distribution residual checks:

Code
res_norm <- DHARMa::simulateResiduals(fittedModel = m8)
plot(res_norm)

The model checks assuming Gamma distribution and log link function:

Code
res_gamma <- DHARMa::simulateResiduals(fittedModel = m9)
plot(res_gamma)

Residual diagnostics are relatively similar, for both distributions so we keep the Gaussian log(response) model specification.

Results

Get phylogenetic signal from glmmTMB Gaussian model:

Code
# get random effect component estimates on SD-scale 
m9_re <- as.data.frame(confint(m9, parm="theta_"))
sigma2_s <- m9_re$Estimate[1]^2 # non-phylogenetic variance
sigma2_p <- m9_re$Estimate[2]^2 # phylogenetic variance estimate

p.signal <- sigma2_p / (sigma2_p + sigma2_s)
p.signal
[1] 0.7369

We found that the phylogenetic species effect explained 83.9% of the total species level random effect variance, and hence the non-phylogenetic effect explained only 16.1% of the total species level random effect variance.

Get model estimated marginals means on the response scale:

Code
# Estimated marginal means on the response scale (odds)
emm_m9 <- emmeans(m9, ~ group, type = "response")
emm_m9
 group       response   SE  df asymp.LCL asymp.UCL
 Angiosperms     2.21 1.03 Inf     0.883      5.53
 Gymnosperms     4.24 1.25 Inf     2.384      7.54

Confidence level used: 0.95 
Intervals are back-transformed from the log scale 
Code
# Get the contrast between the two groups
group_diff <- contrast(emm_m9, method = "pairwise", reverse=TRUE) |> 
  summary(infer = TRUE, type = "response")


# Plot
ggplot(group_diff, aes(y = contrast, x = ratio)) +
  geom_point(size = 3, colour = "#6BAF92") +
  geom_errorbar(aes(xmin = asymp.LCL, xmax = asymp.UCL), 
                width = 0.2, colour = "#6BAF92") +
  geom_vline(xintercept = 1, linetype = "dashed", colour = "grey40") +
  labs(y = NULL, x = "",
       title = "kS contrast: Angiosperms vs Gymnosperms") +
  theme_bw() +
  theme(legend.position = "none")

5 References

Barnard, J. and Rubin, D.B. (1999). Small sample degrees of freedom with multiple imputation. Biometrika, 86, 948-955.

Brooks, M. E., Kristensen, K., van Benthem, K. J., Magnusson, A., Berg, C. W., Nielsen, A., Skaug, H. J.,Machler, M., & Bolker, B. M. (2017). glmmTMB balances speed and flexibility among packages for zero-inflated generalized linear mixed modeling. R Journal, 9 (2), 378–400. https://doi.org/10.32614/RJ-2017-066

Dunn, P. O., Armenta, J. K., & Whittingham, L. A. (2015). Natural and sexual selection act on different axes of variation in avian plumage color. Science Advances, 1(2), e1400155. https://doi.org/10.1126/sciadv.1400155

Hadfield, J. D. (2024, May). MCMCglmm: MCMC Generalised Linear Mixed Models. Retrieved October 7, 2024, from https://cran.r-project.org/web/packages/MCMCglmm/index.html

Hill, G. E., & McGraw, K. J. (2006). Bird Coloration, Volume 2: Function and Evolution. Harvard University Press. https://doi.org/10.2307/j.ctv22jnr8k

Kristensen, K., & McGillycuddy, M. (2025). Covariance structures with glmmTMB. https://cran.r-project. org/web/packages/glmmTMB/vignettes/covstruct.html

McGillycuddy, M. (2023). Model-Based Assessment of Treatment Effect in Multivariate Abundance Data [Doctoral dissertation, The University of New South Wales].

Nakagawa, S., & De Villemereuil, P. (2019). A General Method for Simultaneously Accounting for Phylogenetic and Species Sampling Uncertainty via Rubin’s Rules in Comparative Analysis. Systematic Biology, 68(4), 632–641. https://doi.org/10.1093/sysbio/syy089

Rubin, D. B. (1987). Multiple Imputation for Nonresponse in Surveys (1st ed.). John Wiley & Sons, Ltd. https://doi.org/10.1002/9780470316696

Sanchez-Martinez, P., Martinez-Vilalta, J., Dexter, K. G., Segovia, R. A., & Mencuccini, M. (2020). Adaptation and coordinated evolution of plant hydraulic traits. Ecology Letters, 23 (11), 1599–1610. https://doi.org/10.1111/ele.13584

Trugman, A. T., Anderegg, L. D. L., Shaw, J. D., & Anderegg, W. R. L. (2020). Trait velocities reveal that mortality has driven widespread coordinated shifts in forest hydraulic trait composition. Proceedings of the National Academy of Sciences, 117(15), 8532–8538. https://doi.org/10.1073/pnas.1917521117

6 Session information

Code
library(sessioninfo)
library(details)

si <- session_info()
si$packages <- si$packages 
  # |> filter(package %in% c("metafor", "ape", "clubSandwich", "Matrix", "corpcor", "dplyr", "kableExtra", "xtable", "rotl", "Hmisc", "lattice"))

details(si, summary = 'Current session info', open = FALSE)
Current session info

─ Session info ───────────────────────────────────────────────────────────────
 setting  value
 version  R version 4.4.2 (2024-10-31 ucrt)
 os       Windows 11 x64 (build 26100)
 system   x86_64, mingw32
 ui       RTerm
 language (EN)
 collate  English_Australia.utf8
 ctype    English_Australia.utf8
 tz       America/Denver
 date     2025-09-02
 pandoc   3.4 @ C:/Program Files/RStudio/resources/app/bin/quarto/bin/tools/ (via rmarkdown)

─ Packages ───────────────────────────────────────────────────────────────────
 ! package           * version    date (UTC) lib source
   abind               1.4-8      2024-09-12 [1] CRAN (R 4.4.1)
   ape               * 5.8-1      2024-12-16 [1] CRAN (R 4.4.2)
   backports           1.5.0      2024-05-23 [1] CRAN (R 4.4.0)
   bayesplot           1.11.1     2024-02-15 [1] CRAN (R 4.4.1)
   bayestestR        * 0.15.0     2024-10-17 [1] CRAN (R 4.4.2)
   bit                 4.5.0.1    2024-12-03 [1] CRAN (R 4.4.2)
   bit64               4.5.2      2024-09-22 [1] CRAN (R 4.4.1)
   boot                1.3-31     2024-08-28 [1] CRAN (R 4.4.1)
   bridgesampling      1.1-2      2021-04-16 [1] CRAN (R 4.4.1)
   brms              * 2.22.0     2024-09-23 [1] CRAN (R 4.4.1)
   Brobdingnag         1.2-9      2022-10-19 [1] CRAN (R 4.4.1)
   broom               1.0.7      2024-09-26 [1] CRAN (R 4.4.1)
   broom.mixed       * 0.2.9.6    2024-10-15 [1] CRAN (R 4.4.2)
   cachem              1.1.0      2024-05-16 [1] CRAN (R 4.4.1)
   cellranger          1.1.0      2016-07-27 [1] CRAN (R 4.4.1)
   checkmate           2.3.2      2024-07-29 [1] CRAN (R 4.4.1)
   class               7.3-23     2025-01-01 [1] CRAN (R 4.4.2)
   classInt            0.4-11     2025-01-08 [1] CRAN (R 4.4.1)
   cli                 3.6.3      2024-06-21 [1] CRAN (R 4.4.1)
   clipr               0.8.0      2022-02-22 [1] CRAN (R 4.4.1)
   cluster             2.1.8      2024-12-11 [1] CRAN (R 4.4.2)
   clusterGeneration   1.3.8      2023-08-16 [1] CRAN (R 4.4.1)
   coda              * 0.19-4.1   2024-01-31 [1] CRAN (R 4.4.3)
   codetools           0.2-20     2024-03-31 [2] CRAN (R 4.4.2)
   colorspace          2.1-1      2024-07-26 [1] CRAN (R 4.4.1)
   combinat            0.0-8      2012-10-29 [1] CRAN (R 4.4.0)
   corpcor             1.6.10     2021-09-16 [1] CRAN (R 4.4.0)
   crayon              1.5.3      2024-06-20 [1] CRAN (R 4.4.1)
   cubature            2.1.1      2024-07-14 [1] CRAN (R 4.4.1)
   data.table        * 1.16.4     2024-12-06 [1] CRAN (R 4.4.2)
   DBI                 1.2.3      2024-06-02 [1] CRAN (R 4.4.1)
   DEoptim             2.2-8      2022-11-11 [1] CRAN (R 4.4.1)
   desc                1.4.3      2023-12-10 [1] CRAN (R 4.4.1)
   deSolve             1.40       2023-11-27 [1] CRAN (R 4.4.1)
   details           * 0.3.0      2022-03-27 [1] CRAN (R 4.4.1)
   devtools          * 2.4.5      2022-10-11 [1] CRAN (R 4.4.2)
   DHARMa            * 0.4.7      2024-10-18 [1] CRAN (R 4.4.3)
   digest              0.6.37     2024-08-19 [1] CRAN (R 4.4.1)
   distributional      0.5.0      2024-09-17 [1] CRAN (R 4.4.1)
   doParallel          1.0.17     2022-02-07 [1] CRAN (R 4.4.1)
   dplyr             * 1.1.4      2023-11-17 [1] CRAN (R 4.4.1)
   e1071               1.7-16     2024-09-16 [1] CRAN (R 4.4.2)
   ellipsis            0.3.2      2021-04-29 [1] CRAN (R 4.4.1)
   emmeans           * 1.10.6     2024-12-12 [1] CRAN (R 4.4.2)
   estimability        1.5.1      2024-05-12 [1] CRAN (R 4.4.1)
   evaluate            1.0.3      2025-01-10 [1] CRAN (R 4.4.2)
   expm                1.0-0      2024-08-19 [1] CRAN (R 4.4.1)
   farver              2.1.2      2024-05-13 [1] CRAN (R 4.4.1)
   fastmap             1.2.0      2024-05-15 [1] CRAN (R 4.4.1)
   fastmatch           1.1-6      2024-12-23 [1] CRAN (R 4.4.2)
   fmesher             0.2.0      2024-11-06 [1] CRAN (R 4.4.2)
   forcats           * 1.0.0      2023-01-29 [1] CRAN (R 4.4.1)
   foreach             1.5.2      2022-02-02 [1] CRAN (R 4.4.1)
   fs                  1.6.5      2024-10-30 [1] CRAN (R 4.4.2)
   furrr               0.3.1      2022-08-15 [1] CRAN (R 4.4.1)
   future              1.34.0     2024-07-29 [1] CRAN (R 4.4.1)
   future.apply        1.11.3     2024-10-27 [1] CRAN (R 4.4.2)
   gap                 1.6        2024-08-27 [1] CRAN (R 4.4.2)
   gap.datasets        0.0.6      2023-08-25 [1] CRAN (R 4.4.0)
   geiger            * 2.0.11     2023-04-03 [1] CRAN (R 4.4.1)
   generics            0.1.3      2022-07-05 [1] CRAN (R 4.4.1)
   geometry            0.5.0      2024-08-31 [1] CRAN (R 4.4.1)
   ggplot2           * 3.5.1      2024-04-23 [1] CRAN (R 4.4.1)
   glmmTMB           * 1.1.11     2025-04-03 [1] Github (coraliewilliams/glmmTMB@5872941)
   glmnet              4.1-8      2023-08-22 [1] CRAN (R 4.4.2)
   globals             0.16.3     2024-03-08 [1] CRAN (R 4.4.0)
   glue                1.8.0      2024-09-30 [1] CRAN (R 4.4.2)
   gridExtra           2.3        2017-09-09 [1] CRAN (R 4.4.1)
   gtable              0.3.6      2024-10-25 [1] CRAN (R 4.4.2)
   here              * 1.0.1      2020-12-13 [1] CRAN (R 4.4.1)
   hms                 1.1.3      2023-03-21 [1] CRAN (R 4.4.1)
   htmltools           0.5.8.1    2024-04-04 [1] CRAN (R 4.4.1)
   htmlwidgets         1.6.4      2023-12-06 [1] CRAN (R 4.4.1)
   httpuv              1.6.15     2024-03-26 [1] CRAN (R 4.4.1)
   httr                1.4.7      2023-08-15 [1] CRAN (R 4.4.1)
   igraph              2.1.3      2025-01-07 [1] CRAN (R 4.4.2)
   INLA              * 24.06.27   2024-06-27 [1] local
   inline              0.3.21     2025-01-09 [1] CRAN (R 4.4.1)
   insight             1.0.1      2025-01-10 [1] CRAN (R 4.4.1)
   iterators           1.0.14     2022-02-05 [1] CRAN (R 4.4.1)
   jomo                2.7-6      2023-04-15 [1] CRAN (R 4.4.2)
   jsonlite            1.8.9      2024-09-20 [1] CRAN (R 4.4.1)
   KernSmooth          2.23-26    2025-01-01 [1] CRAN (R 4.4.2)
   knitr             * 1.49       2024-11-08 [1] CRAN (R 4.4.2)
   labeling            0.4.3      2023-08-29 [1] CRAN (R 4.4.0)
   later               1.4.1      2024-11-27 [1] CRAN (R 4.4.2)
   lattice             0.22-6     2024-03-20 [2] CRAN (R 4.4.2)
   lifecycle           1.0.4      2023-11-07 [1] CRAN (R 4.4.1)
   lightr              1.8.0      2024-12-01 [1] CRAN (R 4.4.2)
   listenv             0.9.1      2024-01-29 [1] CRAN (R 4.4.1)
   lme4                1.1-37     2025-03-26 [1] CRAN (R 4.4.2)
   loo                 2.8.0      2024-07-03 [1] CRAN (R 4.4.1)
   lubridate         * 1.9.4      2024-12-08 [1] CRAN (R 4.4.2)
   magic               1.6-1      2022-11-16 [1] CRAN (R 4.4.1)
   magick              2.8.5      2024-09-20 [1] CRAN (R 4.4.1)
   magrittr            2.0.3      2022-03-30 [1] CRAN (R 4.4.1)
   maps              * 3.4.2.1    2024-11-10 [1] CRAN (R 4.4.2)
   MASS              * 7.3-64     2025-01-04 [1] CRAN (R 4.4.2)
   Matrix            * 1.7-1      2024-10-18 [1] CRAN (R 4.4.2)
   matrixStats         1.5.0      2025-01-07 [1] CRAN (R 4.4.2)
   MCMCglmm          * 2.36       2024-05-06 [1] CRAN (R 4.4.1)
   memoise             2.0.1      2021-11-26 [1] CRAN (R 4.4.1)
   mgcv                1.9-1      2023-12-21 [2] CRAN (R 4.4.2)
   mice              * 3.17.0     2024-11-27 [1] CRAN (R 4.4.2)
   mime                0.12       2021-09-28 [1] CRAN (R 4.4.0)
   miniUI              0.1.1.1    2018-05-18 [1] CRAN (R 4.4.1)
   minqa               1.2.8      2024-08-17 [1] CRAN (R 4.4.1)
   misc3d              0.9-1      2021-10-07 [1] CRAN (R 4.4.1)
   mitml             * 0.4-5      2023-03-08 [1] CRAN (R 4.4.3)
   mnormt              2.1.1      2022-09-26 [1] CRAN (R 4.4.0)
   multcomp            1.4-26     2024-07-18 [1] CRAN (R 4.4.2)
   munsell             0.5.1      2024-04-01 [1] CRAN (R 4.4.1)
   mvtnorm             1.3-2      2024-11-04 [1] CRAN (R 4.4.2)
   nlme                3.1-166    2024-08-14 [1] CRAN (R 4.4.1)
   nloptr              2.2.1      2025-03-17 [1] CRAN (R 4.4.3)
   nnet                7.3-20     2025-01-01 [1] CRAN (R 4.4.2)
   numDeriv            2016.8-1.1 2019-06-06 [1] CRAN (R 4.4.0)
   optimParallel       1.0-2      2021-02-11 [1] CRAN (R 4.4.1)
   pacman              0.5.1      2019-03-11 [1] CRAN (R 4.4.1)
   pan                 1.9        2023-08-21 [1] CRAN (R 4.4.2)
   parallelly          1.41.0     2024-12-18 [1] CRAN (R 4.4.2)
   pavo              * 2.9.0      2023-09-24 [1] CRAN (R 4.4.1)
   performance       * 0.12.4     2024-10-18 [1] CRAN (R 4.4.2)
   phangorn            2.12.1     2024-09-17 [1] CRAN (R 4.4.1)
   phyr              * 1.1.0      2020-12-18 [1] CRAN (R 4.4.1)
   phytools          * 2.4-4      2025-01-08 [1] CRAN (R 4.4.2)
   pillar              1.10.1     2025-01-07 [1] CRAN (R 4.4.2)
   pkgbuild            1.4.6      2025-01-16 [1] CRAN (R 4.4.1)
   pkgconfig           2.0.3      2019-09-22 [1] CRAN (R 4.4.1)
   pkgload             1.4.0      2024-06-28 [1] CRAN (R 4.4.1)
   plot3D              1.4.1      2024-02-06 [1] CRAN (R 4.4.1)
   plyr                1.8.9      2023-10-02 [1] CRAN (R 4.4.1)
   png                 0.1-8      2022-11-29 [1] CRAN (R 4.4.0)
   posterior           1.6.1      2025-02-27 [1] CRAN (R 4.4.3)
   profvis             0.4.0      2024-09-20 [1] CRAN (R 4.4.1)
   progressr           0.15.1     2024-11-22 [1] CRAN (R 4.4.2)
   promises            1.3.2      2024-11-28 [1] CRAN (R 4.4.2)
   proxy               0.4-27     2022-06-09 [1] CRAN (R 4.4.1)
   purrr             * 1.0.2      2023-08-10 [1] CRAN (R 4.4.1)
   quadprog            1.5-8      2019-11-20 [1] CRAN (R 4.4.0)
   QuickJSR            1.5.1      2025-01-08 [1] CRAN (R 4.4.2)
   R6                  2.6.1      2025-02-15 [1] CRAN (R 4.4.2)
   rbenchmark        * 1.0.0      2012-08-30 [1] CRAN (R 4.4.0)
   rbibutils           2.3        2024-10-04 [1] CRAN (R 4.4.1)
   Rcpp              * 1.0.14     2025-01-12 [1] CRAN (R 4.4.2)
 D RcppParallel        5.1.9      2024-08-19 [1] CRAN (R 4.4.1)
   Rdpack              2.6.3      2025-03-16 [1] CRAN (R 4.4.3)
   readr             * 2.1.5      2024-01-10 [1] CRAN (R 4.4.1)
   readxl            * 1.4.3      2023-07-06 [1] CRAN (R 4.4.1)
   reformulas          0.4.0      2024-11-03 [1] CRAN (R 4.4.2)
   remotes             2.5.0      2024-03-17 [1] CRAN (R 4.4.1)
   reshape2            1.4.4      2020-04-09 [1] CRAN (R 4.4.1)
   rlang               1.1.5      2025-01-17 [1] CRAN (R 4.4.1)
   rmarkdown         * 2.29       2024-11-04 [1] CRAN (R 4.4.2)
   rpart               4.1.24     2025-01-07 [1] CRAN (R 4.4.2)
   rprojroot           2.0.4      2023-11-05 [1] CRAN (R 4.4.1)
   rstan               2.32.6     2024-03-05 [1] CRAN (R 4.4.1)
   rstantools          2.4.0      2024-01-31 [1] CRAN (R 4.4.1)
   rstudioapi          0.17.1     2024-10-22 [1] CRAN (R 4.4.2)
   sandwich            3.1-1      2024-09-15 [1] CRAN (R 4.4.1)
   scales              1.3.0      2023-11-28 [1] CRAN (R 4.4.1)
   scatterplot3d       0.3-44     2023-05-05 [1] CRAN (R 4.4.0)
   sessioninfo       * 1.2.2      2021-12-06 [1] CRAN (R 4.4.1)
   sf                  1.0-19     2024-11-05 [1] CRAN (R 4.4.2)
   shape               1.4.6.1    2024-02-23 [1] CRAN (R 4.4.0)
   shiny               1.10.0     2024-12-14 [1] CRAN (R 4.4.2)
   sp                  2.1-4      2024-04-30 [1] CRAN (R 4.4.1)
   splitstackshape   * 1.4.8      2019-04-21 [1] CRAN (R 4.4.1)
   StanHeaders         2.32.10    2024-07-15 [1] CRAN (R 4.4.1)
   stringi             1.8.4      2024-05-06 [1] CRAN (R 4.4.0)
   stringr           * 1.5.1      2023-11-14 [1] CRAN (R 4.4.1)
   subplex             1.9        2024-07-05 [1] CRAN (R 4.4.1)
   survival            3.8-3      2024-12-17 [1] CRAN (R 4.4.2)
   tensorA             0.36.2.1   2023-12-13 [1] CRAN (R 4.4.0)
   TH.data             1.1-3      2025-01-17 [1] CRAN (R 4.4.2)
   tibble            * 3.2.1      2023-03-20 [1] CRAN (R 4.4.1)
   tidyr             * 1.3.1      2024-01-24 [1] CRAN (R 4.4.1)
   tidyselect          1.2.1      2024-03-11 [1] CRAN (R 4.4.1)
   tidyverse         * 2.0.0      2023-02-22 [1] CRAN (R 4.4.2)
   timechange          0.3.0      2024-01-18 [1] CRAN (R 4.4.1)
 D TMB                 1.9.17     2025-03-10 [1] CRAN (R 4.4.3)
   tzdb                0.4.0      2023-05-12 [1] CRAN (R 4.4.1)
   units               0.8-5      2023-11-28 [1] CRAN (R 4.4.1)
   urlchecker          1.0.1      2021-11-30 [1] CRAN (R 4.4.1)
   usethis           * 3.1.0      2024-11-26 [1] CRAN (R 4.4.2)
   utf8                1.2.4      2023-10-22 [1] CRAN (R 4.4.1)
   vctrs               0.6.5      2023-12-01 [1] CRAN (R 4.4.1)
   vroom             * 1.6.5      2023-12-05 [1] CRAN (R 4.4.1)
   withr               3.0.2      2024-10-28 [1] CRAN (R 4.4.2)
   xfun                0.50       2025-01-07 [1] CRAN (R 4.4.2)
   xml2                1.3.6      2023-12-04 [1] CRAN (R 4.4.1)
   xtable              1.8-4      2019-04-21 [1] CRAN (R 4.4.2)
   yaml                2.3.10     2024-07-26 [1] CRAN (R 4.4.1)
   zoo                 1.8-12     2023-04-13 [1] CRAN (R 4.4.1)

 [1] C:/Users/z5394590/AppData/Local/R/win-library/4.4
 [2] C:/Program Files/R/R-4.4.2/library

 D ── DLL MD5 mismatch, broken installation.

──────────────────────────────────────────────────────────────────────────────


Note
This site may still be updated, and could be small mistakes.

Bird icon created by Smashicons - Flaticon